package ;

import easelhx.display.Graphics;
import easelhx.display.Shape;
import easelhx.display.Stage;
import easelhx.display.Text;
import easelhx.events.MouseEvent;
import easelhx.geom.Point;
import easelhx.ui.Touch;
import easelhx.utils.Ticker;
import js.HTMLCanvasElement;
import js.Lib;

/**
 * ...
 * @author 
 */

class CurveToExample implements IExample
{

	private var canvas:HTMLCanvasElement;
	private var stage:Stage;
	private var g:Graphics;
	private var shape:Shape;
	private var isMouseDown:Bool;
	private var oldPosition:Point;
	private var currentShape:Shape;
	private var ctx:Dynamic;
	private var selectedColor:Dynamic;
	private var oldMidX:Float;
	private var oldMidY:Float;
	private var oldX:Float;
	private var oldY:Float;
	private var firstLoad:Bool;
	private var txt:Text;
	
	public function new() 
	{
		canvas = cast Lib.document.getElementById("testCanvas");
		stage =  new Stage(canvas);
	}
	
	/* INTERFACE IExample */
	
	public function run():Void 
	{
		oldX = 0.0;
		oldY = 0.0;
		firstLoad = true;
		txt = new Text("Click and Drag to Draw", "36px Arial", "#777777");
		txt.x = 300;
		txt.y = 200;
		ctx = canvas.getContext("2d");
		oldPosition = new Point(stage.mouseX, stage.mouseY);
		stage.autoClear = true;
		
		Reflect.setField(stage, MouseEvent.onMouseDown, handleMouseDown);
		Reflect.setField(stage, MouseEvent.onMouseUp, handleMouseUp);

		Touch.enable(stage);

		stage.addChild(txt);
		stage.update();
		Ticker.addListener(this);
	}
	
	private function stop() {
		Ticker.removeListener(this);
	}

	private function tick() {
		if (isMouseDown) {
			var pt:Point = new Point(stage.mouseX, stage.mouseY);
			var midPoint:Point = new Point(Std.int(oldX + pt.x) >> 1, Std.int(oldY + pt.y) >> 1);
			currentShape.graphics.moveTo(midPoint.x, midPoint.y);
			currentShape.graphics.curveTo(oldX, oldY, oldMidX, oldMidY);
			currentShape.draw(ctx);

			oldX = pt.x;
			oldY = pt.y;

			oldMidX = midPoint.x;
			oldMidY = midPoint.y;

			stage.update();
		}
	}

	private function handleMouseDown(e) {
		isMouseDown = true;
		if (firstLoad) {
			stage.removeChild(txt);
		}
		firstLoad = false;
		var s:Shape = new Shape();
		oldX = stage.mouseX;
		oldY = stage.mouseY;
		oldMidX = stage.mouseX;
		oldMidY = stage.mouseY;
		var g:Graphics = s.graphics;
		var thickness = Std.int(Math.random() * 30 + 10);
		g.setStrokeStyle(thickness + 1, 'round', 'round');
		selectedColor = Graphics.getRGB( Std.int(Math.random() * 255), Std.int(Math.random() * 255), Std.int(Math.random() * 255));
		g.beginStroke(selectedColor);
		stage.addChild(s);
		currentShape = s;
	}

	private function handleMouseUp(e) {
		isMouseDown = false;
	}
	
}